import { useEffect, useImperativeHandle, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Modal, Upload } from 'antd';
import type { RcFile, UploadProps } from 'antd/es/upload';
import ImgCrop from 'antd-img-crop';
import type { UploadFile } from 'antd/es/upload/interface';
import { uploadFile } from '@/api/upload';

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });

const UploadFile = (props: { submit?: any; text?: any; max?: any; isCrop?: boolean; disabled?: boolean; remove?: any; list?: Array<string>; aspect?: number, type: number, onRef?: any }) => {
    let { text, max = 1, type = 1, list, aspect = 1 / 1, isCrop = false, disabled = false } = props;
    //用useImperativeHandle暴露一些外部ref能访问的属性
    useImperativeHandle(props.onRef, () => {
        return {
            resetFileList: resetFileList,
        };
    });
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [loading, setLoading] = useState<boolean>(false)

    useEffect(() => {
        if (list && list.length) {
            let dataList: UploadFile[] = [];
            list.map((item) => {
                let name = item.substring(item.lastIndexOf('/') + 1);
                dataList.push({
                    uid: name,
                    name: name,
                    status: 'done',
                    url: item
                })
            })
            setFileList(dataList)
        } else {
            setFileList([])
        }
    }, [list])

    //设置upload列表
    const resetFileList = (list: any[]) => {
        if (list && list.length) {
            let dataList: UploadFile[] = [];
            list.map((item) => {
                let name = item.substring(item.lastIndexOf('/') + 1);
                dataList.push({
                    uid: name,
                    name: name,
                    status: 'done',
                    url: item
                })
            })
            setFileList(dataList)
        } else {
            setFileList([])
        }
    }

    //上传操作
    const fileRequest = async (options: { onSuccess?: any; onError?: any; file: any }) => {
        const { onSuccess, onError, file } = options;
        try {
            let formData = new FormData()
            formData.append('file', file)
            let res = await uploadFile(type, formData);
            let { data: fileData } = res;
            props.submit({ fileData, name: file.name });
            onSuccess(res);
        } catch (err) {
            console.log(err)
            onError({ err })
        } finally {
        }
    }

    const handleCancel = () => setPreviewOpen(false);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    //文件变化
    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList);
    }
    //移除
    const handleRemove = (e: any) => {
        console.log(e)
        let { status } = e;
        if (status == 'removed') {
            let { data } = e.response
            props.remove(data)
        } else if (status == 'done') {
            props.remove({
                fileId: e.uid,
                filePath: e.url
            })
        }
    }


    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>{text ? text : '上传文件'}</div>
        </div>
    );
    return (
        <>
            {
                isCrop ? (
                    <ImgCrop rotationSlider quality={1} aspect={aspect}>
                        <Upload
                            customRequest={fileRequest}
                            listType="picture-card"
                            fileList={fileList}
                            maxCount={max}
                            disabled={disabled}
                            multiple={max > 1 ? true : false}
                            onPreview={handlePreview}
                            onChange={handleChange}
                            onRemove={handleRemove}
                        >
                            {
                                fileList.length >= max ? null : uploadButton
                            }
                        </Upload>
                    </ImgCrop>
                ) : (
                    <Upload
                        customRequest={fileRequest}
                        listType="picture-card"
                        fileList={fileList}
                        maxCount={max}
                        disabled={disabled}
                        multiple={max > 1 ? true : false}
                        onPreview={handlePreview}
                        onChange={handleChange}
                        onRemove={handleRemove}
                    >
                        {
                            fileList.length >= max ? null : uploadButton
                        }
                    </Upload>
                )
            }
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </>
    );
};

export default UploadFile;